package com.nguyen.views;

import java.util.ArrayList;

import android.content.Context;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.nguyen.adapters.ListCategoryAdapter;
import com.nguyen.entities.Category;
import com.nguyen.letcook.LetCookActivity;
import com.nguyen.letcook.R;
import com.nguyen.service.Service;

public class ListCategoryView extends RelativeLayout implements OnItemClickListener, OnClickListener{

	boolean isNeedToLoadFromServer = true;
	Button btnBack;
	ListCategoryAdapter mAdapter;
	Context mContext;
	
	public ListCategoryView(Context context, boolean isLoadFromServer) {
		super(context);
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(R.layout.list_category, this, true);
		
		btnBack = (Button) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(this);
		
		ListView lstCategory = (ListView) findViewById(R.id.listCategory);		
		mAdapter = new ListCategoryAdapter(context);
		lstCategory.setAdapter(mAdapter);
		lstCategory.setOnItemClickListener(this);
		
		this.mContext = context;
		isNeedToLoadFromServer = isLoadFromServer;
		if(isNeedToLoadFromServer)
			new LoadCategoryFromServer().execute();
	}

	class LoadCategoryFromServer extends AsyncTask<Void, Void, ArrayList<Category>>{
		
		@Override
		public void onPreExecute(){
			
		}
		
		@Override
		public ArrayList<Category> doInBackground(Void...params){
			ArrayList<Category> ret = null;
			Service service = new Service();
			ret = service.getListCategory();
			return ret;
		}
		
		@Override
		public void onPostExecute(ArrayList<Category> res){
			if(res != null){
				for(Category item : res){
					mAdapter.addItem(item);
				}
				mAdapter.notifyDataSetChanged();
			}
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		LetCookActivity activity = (LetCookActivity) mContext;
		activity.setDishView(mAdapter.getCategoryId(arg2));
		
	}
	
	@Override
	public void onClick(View v){
		if(v == btnBack){
			// when click back button do nothing.
			LetCookActivity activity = (LetCookActivity) mContext;
			activity.setDishView(-1);
		}
	}
}
